<template>
  <div>
    <Header :title="'返回'" :subTitle="'营销活动'" :hasBackPath="true" @headerBack="headerBack"></Header>
    <a-card :bordered="false">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48" @keyup.enter.native="searchList">
            <a-col :xxl="6" :lg="8" :md="12" :sm="24">
              <a-form-item label="单号">
                <a-input v-model="queryParam.orderNo" placeholder="" allowClear />
              </a-form-item>
            </a-col>
            <a-col :xxl="6" :lg="8" :md="12" :sm="24">
              <a-form-item label="集团卡号">
                <a-input v-model="queryParam.jnbyCardno" placeholder="" allowClear />
              </a-form-item>
            </a-col>
            <a-col :xxl="6" :lg="8" :md="12" :sm="24">
              <a-form-item label="手机号">
                <a-input v-model="queryParam.phone" placeholder="" allowClear />
              </a-form-item>
            </a-col>
            <a-col :xxl="6" :lg="8" :md="12" :sm="24">
              <a-form-item label="活动时间">
                <a-range-picker
                  style="width: 100%"
                  format="YYYY-MM-DD HH:mm:ss"
                  :placeholder="['开始时间', '结束时间']"
                  :show-time="{
                    hideDisabledOptions: true,
                    defaultValue: [moment('00:00:00', 'HH:mm:ss'), moment('23:59:59', 'HH:mm:ss')]
                  }"
                  v-model="queryParam.timePicker"
                />
              </a-form-item>
            </a-col>
            <a-col :xxl="6" :lg="8" :md="12" :sm="24" v-if="queryParam.rewardType == 2">
              <a-form-item label="快递单号">
                <a-input v-model="queryParam.logisticsNo" placeholder="" allowClear />
              </a-form-item>
            </a-col>
            <a-col :xxl="queryParam.rewardType == 1 ? 24 : 18" :lg="queryParam.rewardType == 1 ? 16 : 8" :md="queryParam.rewardType == 1 ? 24 : 12" :sm="24">
              <span class="table-page-search-submitButtons" :style="{ float: 'right', overflow: 'hidden' }">
                <a-button type="primary" @click="searchList">查询</a-button>
                <a-button style="margin-left: 8px" @click="resetList">重置</a-button>
                <template v-if="queryParam.rewardType == 2">
                  <!-- <a-popconfirm title="确定导出当前条件下的明细?" ok-text="Yes" cancel-text="No" @confirm="handleExport" class="export">
                    <a-button style="margin-left: 8px" type="primary" icon="download">导出</a-button>
                  </a-popconfirm> -->
                  <!-- <a-button style="margin-left: 8px" type="primary" icon="download" @click="handleExport">导出</a-button> -->
                  <a-button style="margin-left: 8px" icon="plus" @click="handleImportXls">导入</a-button>
                </template>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <a-tabs :activeKey="queryParam.rewardType" @change="tabsChange">
        <a-tab-pane :key="1" tab="优惠券"></a-tab-pane>
        <a-tab-pane :key="2" tab="实物"></a-tab-pane>
      </a-tabs>
      <s-table
        ref="table"
        size="default"
        :rowKey="record => record.id"
        :columns="queryParam.rewardType == 1 ? couponsColumns : goodsColumns"
        :data="loadData"
        :pagination="paginationProps"
        :scroll="{ x: queryParam.rewardType == 1 ? 1200 : 1800 }"
      >
        <span slot="voucherNo" slot-scope="text">
          <ellipsis :length="20" tooltip>{{ text }}</ellipsis>
        </span>
        <span slot="action" slot-scope="text, record">
          <a @click="handleAddress(record)">编辑地址</a>
        </span>
      </s-table>
    </a-card>
    <AddressList ref="address" :unionId="unionId" :defLogistic="logistic" @newAddress="newAddress" :title="'选择地址'"></AddressList>
    <j-import-modal ref="importModal" :url="getImportUrl()" :uploadParams="getUploadParams()" @ok="importOk" :templateUrl="templateUrl()" :serviceId="7"></j-import-modal>
    <ExportModal ref="exportModal"></ExportModal>
  </div>
</template>
<script>
import { listMixin } from '@/views/box/util/listMixin'
import moment from 'moment'
import 'moment/locale/zh-cn'
import globalData from '@/assets/js/common'
import { queryUploadSuccess, fetchExportFileId } from '@/components/qiniuUpload/common'
import Header from '@/views/box/components/layouts/Header'
import AddressList from '@/views/box/components/Address/AddressList'
import JImportModal from '@/components/qiniuUpload/JImportModal'
import ExportModal from '@/components/qiniuUpload/ExportModal'
import { marketingActivityDetaiList, marketingActivityEditLogistics, marketingActivityDownloadDetail } from '@/api/box/marketing'
import { couponsColumns, goodsColumns } from './table'
export default {
  mixins: [listMixin],
  components: { Header, AddressList, JImportModal, ExportModal },
  data() {
    return {
      couponsColumns,
      goodsColumns,
      queryParam: {
        rewardType: 1
      },
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => this.fetchData(parameter),
      editRecord: {},
      logistic: {
        id: ''
      },
      unionId: '',
      actId: '',
      timer: null
    }
  },
  deactivated() {
    this.$destroy()
  },
  methods: {
    moment,
    headerBack() {
      this.$router.back()
    },
    resetList() {
      let query = JSON.parse(JSON.stringify(this.queryParam))
      let type = query.rewardType
      this.queryParam = {
        rewardType: type
      }
      this.$refs.table.refresh(true)
    },
    fetchData(parameter) {
      this.actId = this.$route.params.id
      let formValue = this.filterFields(this.queryParam)
      let params = {
        page: parameter,
        requestData: { ...formValue, activityId: this.actId }
      }
      try {
        return this.fetchList(params, marketingActivityDetaiList).then(res => {
          if (res.code == 0) {
            return res
          } else {
            this.$message.warning(res.msg)
            return {
              data: [],
              page: {
                pageNo: 1,
                pageSize: 10,
                count: 0
              }
            }
          }
        })
      } catch (err) {
        console.log(err.response)
      }
    },
    filterFields(values) {
      const formValue = {}
      Object.keys(values).forEach(i => {
        if (values[i] !== '' && values[i] !== undefined && values[i] !== null) {
          if (i == 'timePicker') {
            formValue.startTime = values[i][0].format('YYYY-MM-DD HH:mm:ss')
            formValue.endTime = values[i][1].format('YYYY-MM-DD HH:mm:ss')
          } else {
            formValue[i] = values[i]
          }
        }
      })
      return formValue
    },
    tabsChange(key) {
      this.queryParam.rewardType = key
      this.$refs.table.refresh(true)
    },
    // 编辑地址
    handleAddress(record) {
      this.editRecord = record
      this.unionId = record.unionid
      this.logistic = {
        id: record.addressId
      }
      this.$refs.address.show()
    },
    newAddress(record) {
      console.log(record)
      let params = {
        requestData: {
          addressId: record.id,
          id: this.editRecord.id
        }
      }
      marketingActivityEditLogistics(params).then(res => {
        if (res.code == 0) {
          this.$message.success('编辑成功')
          this.$refs.table.refresh()
        } else {
          this.$message.warning(res.msg)
        }
      })
    },
    // 导入
    handleImportXls() {
      this.$refs.importModal.show()
    },
    // 处理上传业务的后台地址
    getImportUrl() {
      return ''
    },
    getUploadParams() {
      // console.log({...globalData.uploadParams})
      return { ...globalData.uploadParams }
    },
    // 上传成功后的方法
    importOk(result, fileList) {
      let that = this
      queryUploadSuccess(this.timer, result, 60000, function(x) {
        console.log(x)
        if (x == 'done' || x == 'warning') {
          that.$refs.importModal.close()
          that.$refs.table.refresh(true)
        }
        if (x == 'done') {
          console.log(fileList)
        }
      })
    },
    templateUrl() {
      return 'https://img.bzhz.jnbygroup.com/actDetailListTemp.xlsx'
    },
    // 导出
    async handleExport() {
      // let param = this.filterFields(this.queryParam)
      let result = await this.fetchDownloadDetail()
      if (result) {
        this.$refs.exportModal.show(result)
      }
    },
    fetchDownloadDetail() {
      let formValue = this.filterFields(this.queryParam)
      let params = {
        requestData: { ...formValue, activityId: this.actId },
        page: {
          pageNo: 1,
          pageSize: 10
        }
      }
      return marketingActivityDownloadDetail(params).then(res => {
        if (res.code == 0) {
          return res.data
        }
      })
    }
  }
}
</script>

